package tt.com.warehousemanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import tt.com.common.model.YxCommonProviders;
import tt.com.common.util.PageUtil;
import tt.com.warehousemanager.mapper.ProviderMapper;
import tt.com.warehousemanager.service.ProvidersService;

import java.util.Date;

/**
 * @author Czycka
 * @date 2022/8/22 17:20
 * @description 供应商实现类
 */
@Service
public class ProvidersServiceImpl extends ServiceImpl<ProviderMapper, YxCommonProviders> implements ProvidersService {
    @Override
    public Integer insertProvider(YxCommonProviders provider, String createUserId) {
        QueryWrapper<YxCommonProviders> wrapper = new QueryWrapper<>();
        wrapper.eq("code", provider.getCode());
        if (baseMapper.selectOne(wrapper) != null) {
            // 重复添加返回-1
            return -1;
        }
        // 设置创建时间
        provider.setCreateTime(new Date());
        // 设置创建操作人id
        provider.setCreateUserId(createUserId);
        return baseMapper.insert(provider);
    }

    @Override
    public Integer deleteProvider(Long id, String deleteUserId) {
        // 根据 id 获取数据库内的供应商
        YxCommonProviders providers = baseMapper.selectById(id);
        if (providers == null) {
            // 若数据不存在则返回 -1
            return -1;
        }
        if (providers.getDataStatus() == 1) {
            // 若数据已被删除则返回 -2
            return -2;
        }
        // 设置删除时间
        providers.setDeleteTime(new Date());
        // 设置删除操作人id
        providers.setDeleteUserId(deleteUserId);
        baseMapper.updateById(providers);
        return baseMapper.deleteById(providers.getId());

    }

    @Override
    public Integer updateProvider(YxCommonProviders provider, String updateUserId) {
        // 设置修改时间
        provider.setLastUpdateTime(new Date());
        // 设置修改操作人id
        provider.setLastUpdateUserId(updateUserId);
        return baseMapper.updateById(provider);
    }

    @Override
    public PageUtil showProviderByPage(PageUtil pageUtil) {
        Page<YxCommonProviders> page = new Page<>(pageUtil.getPageIndex(), pageUtil.getPageSize());
        Page<YxCommonProviders> providersPage = baseMapper.selectPage(page, null);
        // 设置总条数 自动计算总页数
        pageUtil.setTotalSize((int) providersPage.getTotal());
        pageUtil.setData(providersPage);
        return pageUtil;
    }
}
